package com.scatteredServer.util;


import com.scatteredServer.exception.FileException;
import io.minio.*;
import io.minio.errors.*;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;


import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author admin
 *
 */
@Slf4j
@Component
public class MinioUtils {

    @Resource
    private MinioClient minioClient;


    /**
     * 上传文件
     * @param file
     * @param bucketName
     * @return
     * @throws Exception
     */
    public String uploadFile(MultipartFile file, String bucketName,String filepath) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        //判断是否存在
        createBucket(bucketName);
        minioClient.putObject(
                PutObjectArgs.builder().bucket(bucketName).object(filepath).stream(
                                file.getInputStream(), file.getSize(), -1)
                        .contentType(file.getContentType())
                        .build());
        return bucketName+filepath;
    }

    /**
     * 通过字节流上传
     * @param imageFullPath
     * @param bucketName
     * @param imageData
     * @return
     */
    public String uploadImage(String imageFullPath,
                              String bucketName,
                              byte[] imageData) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(imageData);

        //判断是否存在
        createBucket(bucketName);
        minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(imageFullPath)
                .stream(byteArrayInputStream,byteArrayInputStream.available(),-1)
                .contentType(".jpg")
                .build());
        return bucketName+"/"+imageFullPath;
    }

    /**
     * 删除文件
     * @param bucketName
     * @param fileName
     * @return
     */
    public void removeFile(String bucketName,String fileName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        //判断桶是否存在
        boolean res=minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (res) {
            //删除文件
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName)
                    .object(fileName).build());
        }else {
            throw new FileException();
        }
    }

    /**
     * 下载文件
     * @param fileName
     * @param bucketName
     * @param response
     */
    public void fileDownload(String bucketName,
                             String fileName,
                             HttpServletResponse response) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {

        InputStream inputStream;
        OutputStream outputStream;
        if (StringUtils.isBlank(fileName)) {
            throw new FileException();
        }
        outputStream = response.getOutputStream();
        // 获取文件对象
        inputStream =minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(fileName).build());
        byte[] buf = new byte[8192];
        int length;
        response.reset();
        response.setHeader("Content-Disposition", "attachment;filename=" +
                URLEncoder.encode(fileName.substring(fileName.lastIndexOf("/") + 1), "UTF-8"));
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("UTF-8");
        // 输出文件
        while ((length = inputStream.read(buf)) > 0) {
            outputStream.write(buf, 0, length);
        }
        log.info("{}桶，下载文件，{}",bucketName,fileName);
        inputStream.close();
        outputStream.close();
    }

    @SneakyThrows
    public void createBucket(String bucketName) {
        //如果不存在就创建
        if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
    }

}
